package cn.com.nes.site.service.system.excel.impl;

import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.common.util.DistinctByPropertyUtils;
import cn.com.nes.common.util.XzqhUtils;
import cn.com.nes.mybatis.agent.project.entity.TProject;
import cn.com.nes.site.entity.em.project.ImportLogsTypeEnum;
import cn.com.nes.site.entity.iot.CustomerSurveyExcel;
import cn.com.nes.site.entity.vo.NullVO;
import cn.com.nes.site.entity.vo.project.ImportGovernmentalCustomerArchiveVO;
import cn.com.nes.site.service.crm.customer.CrmCustomerService;
import cn.com.nes.site.service.crm.customer.CustomerArchiveService;
import cn.com.nes.site.service.crm.customer.dto.CustomerDTO;
import cn.com.nes.site.service.logs.ImportLogDetailsService;
import cn.com.nes.site.service.logs.ImportLogsService;
import cn.com.nes.site.service.project.TProjectService;
import cn.com.nes.site.service.system.excel.GovernmentalCustomerArchivesConsumer;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 政府客户档案导入消费者
 *
 * @Author: ShenWei
 * @Date: 2024/05/15/14:22
 */
@Slf4j
@Service
public class GovernmentalCustomerArchivesConsumerImpl implements GovernmentalCustomerArchivesConsumer {
    @Resource
    CrmCustomerService crmCustomerService;

    @Resource
    private CustomerArchiveService customerArchiveService;

    @Resource
    ImportLogDetailsService importLogDetailsService;

    @Resource
    ImportLogsService importLogsService;

    @Resource
    TProjectService tProjectService;

    @Override
    public void receive(NullVO parentVo, List<CustomerSurveyExcel> list) {
        if (CollectionUtil.isEmpty(list)) return;

        // 将入参转换成具体类型的子类参数 - 父类接参,子类实现
        ImportGovernmentalCustomerArchiveVO childVo = (ImportGovernmentalCustomerArchiveVO) parentVo;

        log.info("开始消费政府客户档案导入信息...");
        CustomerSurveyExcel customerSurveyExcel = new CustomerSurveyExcel();
        try {
            list = checkData(childVo, list);
            HashMap<String, Object> hashMap = null;
            for (int i = 0; i < list.size(); i++) {
                customerSurveyExcel = list.get(i);
                hashMap = new HashMap<>();
                hashMap.put("idCardNumber", customerSurveyExcel.getIdCardNumber() == null ? "" : customerSurveyExcel.getIdCardNumber());
                hashMap.put("projectUuid", childVo.getProjectUuid() == null ? "" : childVo.getProjectUuid());
                hashMap.put("xzqhdm", customerSurveyExcel.getAreaCode() == null ? "" : customerSurveyExcel.getAreaCode());
                hashMap.put("customerName", customerSurveyExcel.getContactName() == null ? "" : customerSurveyExcel.getContactName());
                hashMap.put("phone", customerSurveyExcel.getContactPhone() == null ? "" : customerSurveyExcel.getContactPhone());
                CustomerDTO customerDTO = crmCustomerService.getCustomerByIdCard(hashMap);
                if (ObjectUtil.isNotNull(customerDTO)) {
                    //更新方法
                    childVo.setCustomerUuid(customerDTO.getUuid());
                    customerArchiveService.updateImportInfo(childVo, customerSurveyExcel);
                    DistinctByPropertyUtils.insertDetailsData(importLogDetailsService, customerSurveyExcel, childVo, "同一行政区划下已有数据,更新覆盖操作", ImportLogsTypeEnum.PROJECT_IMPORT.getKey());
                    log.debug("--------更新客户-----------客户名称：{}", customerDTO.getCustomerName());
                } else {
                    // 保存大客户下关联的客户信息
                    customerArchiveService.saveImportInfo(childVo, customerSurveyExcel);
                    log.debug("--------新增客户-----------客户名称：{}", customerSurveyExcel.getContactName());
                }
            }
        } catch (Exception e) {
            log.error("数据导入失败，客户姓名:{},客户电话:{},异常原因:{}", customerSurveyExcel.getContactName(), customerSurveyExcel.getContactPhone(), e.getMessage());
            e.printStackTrace();
        }
        log.info("政府客户档案导入信息消费完成!");
    }

    // 过滤符合导入规则的数据
    private List<CustomerSurveyExcel> checkData(ImportGovernmentalCustomerArchiveVO childVo, List<CustomerSurveyExcel> list) throws Exception {
        TProject projectDetail = tProjectService.getProjectDetail(childVo.getProjectId());
        if (ObjectUtil.isNull(projectDetail)) {
            throw new IllegalBusinessException("项目信息不存在,导入失败!");
        }

        // 保存导入日志主表数据 - 只保存一次
        importLogsService.insertCustomerInfoData(childVo, childVo.getImportDataRowCount());

        // 去重身份证一样的/
        list = DistinctByPropertyUtils.distinctByProperty(list, importLogDetailsService, childVo);

        // 校验其他规则
        List<CustomerSurveyExcel> resList = new ArrayList<>();

        for (CustomerSurveyExcel customerSurveyExcel : list) {
            if (ObjectUtil.isNull(customerSurveyExcel)) {
                continue;
            }

            boolean phoneFlag = false;
            boolean areaCodeFlag = false;
            StringBuilder failMessage = new StringBuilder();

            // 校验电话号为空的
            if (StrUtil.isBlank(customerSurveyExcel.getContactPhone())) {
                phoneFlag = true;
                failMessage.append("手机号为空");
            }

            // 校验行政区划不符合项目行政区划
            String areaCode = customerSurveyExcel.getAreaCode().split("_")[0];

            if (!areaCode.startsWith(XzqhUtils.getRegionCodePrefix(projectDetail.getAreaCode()))) {
                areaCodeFlag = true;
                if (phoneFlag) {
                    failMessage.append("且");
                }
                failMessage.append("行政区划不属于项目覆盖范围");
            }

            if (phoneFlag || areaCodeFlag) {
                DistinctByPropertyUtils.insertDetailsData(importLogDetailsService, customerSurveyExcel, childVo, String.valueOf(failMessage.append(",不能添加")), ImportLogsTypeEnum.PROJECT_IMPORT.getKey());
//                importLogsService.increaseFailCount(childVo, 1);
                continue;
            }
            resList.add(customerSurveyExcel);
        }
        return resList;
    }
}
